package com.self.liu.xp.base;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.self.liu.xp.constant.ServiceConst;
import com.self.liu.xp.thrift.service.ExecuteService.Iface;

public class Executor implements Iface {

    /* log */
    private static Logger logger = Logger.getLogger(Executor.class);

    @Override
    public String execute(String reqJson) {
        try {
            ReqJson req = JSONObject.parseObject(reqJson, ReqJson.class);
            IThriftService service = (IThriftService) Class.forName(
                ServiceConfig.getBusinessName(req.getService())).newInstance();
            Object res = service.doExecute(JSONObject.parseObject(req.getData().toString(),
                service.getReqClass()));
            return createResJson(ServiceConst.RES_SUCCESS, res);
        } catch (ClassNotFoundException e) {
            logger.error("未找到对应业务名称。(req =" + reqJson + ")");
            return createResJson(ServiceConst.RES_SERVICE_NOT_FOUND, null);
        } catch (Exception e) {
            logger.error("请求失败。(req=" + reqJson + ") case:" + e.getMessage());
        }
        return createResJson(ServiceConst.RES_FAIL, null);
    }

    private String createResJson(String code, Object data) {
        return JSONObject.toJSONString(new ResJson(code, data),
            SerializerFeature.DisableCircularReferenceDetect);
    }
}
